<template>
  <div class="app-container" style="padding: 3px;">
    <el-tabs v-model="type" @tab-click="handleTabClick" type="border-card" >
      <el-tab-pane label="文章" name="news">
        <el-row>
          <el-col :span="20">
            <el-radio-group>
              <el-radio-button label="公众号文章素材">公众号文章素材</el-radio-button>
              <el-radio-button label="企业文章素材">企业文章素材</el-radio-button>
            </el-radio-group>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="16" style="margin: 10px 0;">
            <span>文章素材（共{{total}}条）</span>
          </el-col>
          <el-col :span="6">
            <el-input placeholder="请输入文章标题进行搜索">
              <el-button slot="append" icon="el-icon-search"></el-button>
            </el-input>
          </el-col>
          <el-col :span="2" align="right">
            <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
          </el-col>
        </el-row>
        <el-row :gutter="5" class="el-row" type="flex" >
          <el-col :span="4" v-for = "(medium,index) in mediumList" :key="medium.id" class="el-col">
            <el-card class="el-card" :body-style="{padding:'4px'}">
              <div style="padding: 0px;">
                <span class="card-title">{{ medium.content.title}}</span>
                <el-row :gutter="0">
                  <el-col :span="16">
                    <span class="desc">{{ medium.content.desc }}</span>
                  </el-col>
                  <el-col :span="8">
                    <el-image
                      style="width: 50px; height: 50px;float: right"
                      :src="medium.content.imgUrl"
                      fit="fill"></el-image>
                  </el-col>
                </el-row>
              </div>
              <div class="bottom clearfix">
                创建:{{parseTime(medium.createTime, '{y}/{m}/{d} {h}:{i}:{s}') }}
                <el-button type="text" size="mini" class="el-icon-edit" @click="handleUpdate(medium.id)"></el-button>
                <el-button type="text" size="mini" class="el-icon-delete" @click="handleDelete(medium.id)"></el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="链接" name="link">
        <el-row>
          <el-col :span="16" style="margin: 10px 0;">
            <span>链接素材（共{{total}}条）</span>
          </el-col>
          <el-col :span="6">
            <el-input placeholder="请输入文章标题进行搜索">
              <el-button slot="append" icon="el-icon-search"></el-button>
            </el-input>
          </el-col>
          <el-col :span="2" align="right">
            <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
          </el-col>
        </el-row>
        <el-row :gutter="5" class="el-row" type="flex" >
          <el-col :span="4" v-for = "(medium,index) in mediumList" :key="medium.id" class="el-col">
            <el-card :body-style="{padding:'4px'}">
              <div style="padding: 0px;">
                <span class="card-title">{{ medium.content.title}}</span>
                <el-row :gutter="0">
                  <el-col :span="16">
                    <span class="desc">{{ medium.content.desc }}</span>
                  </el-col>
                  <el-col :span="8">
                    <el-image
                      style="width: 50px; height: 50px;float: right"
                      :src="medium.content.imgUrl"
                      fit="fill"></el-image>
                  </el-col>
                </el-row>
              </div>
              <div class="bottom clearfix">
                创建:{{parseTime(medium.createTime, '{y}/{m}/{d} {h}:{i}:{s}') }}
                <el-button type="text" size="mini" class="el-icon-edit" @click="handleUpdate(medium.id)"></el-button>
                <el-button type="text" size="mini" class="el-icon-delete" @click="handleDelete(medium.id)"></el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="海报" name="image">
        <el-row>
          <el-col :span="16" style="margin: 10px 0;">
            <span>海报素材（共{{total}}条）</span>
          </el-col>
          <el-col :span="6">
            <el-input placeholder="请输入图片进行搜索">
              <el-button slot="append" icon="el-icon-search"></el-button>
            </el-input>
          </el-col>
          <el-col :span="2" align="right">
            <el-upload
              class="avatar-uploader"
              :action="uploadFileUrl"
              :headers="headers"
              accept="image/png, image/jpeg"
              :multiple="true"
              :show-file-list="false"
              :file-list="fileList"
              :before-upload="handleFileSizeLimit"
              :on-error="handleUploadError"
              :on-exceed="handleExceed"
              :on-success="handleMultiplUploadSuccess">
              <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
            </el-upload>
          </el-col>
        </el-row>
        <el-row :gutter="5" class="el-row" type="flex"  style="overflow:auto">
          <el-col :span="4" v-for = "(medium,index) in mediumList" :key="medium.id" class="el-col">
            <el-card :body-style="{padding:'4px'}">

              <div style="padding: 0px;height: 180px;">
                  <el-image
                    style="width: 100%; height: 100%;"
                    :src="medium.content.imgUrl"
                    :preview-src-list="[medium.content.imgUrl]"
                    fit="contain"
                    lazy></el-image>
              </div>
              <div>
                <el-input v-if="updateTitleFlagArray[index]"
                          size="mini"
                          v-model="medium.content.title"
                          :ref="'input' + index"
                          @blur="updateTitle(index,medium)"/>
                <el-button v-else
                           type="primary"
                           plain
                           size="mini"
                           :loading="updateTitleFlagArray[index]"
                           @click="handleUpdateTitle(index,medium.id)">
                  {{ medium.content.title}}<i class="el-icon-edit el-icon--right"/>
                </el-button>
              </div>
              <div class="bottom clearfix">
                创建:{{parseTime(medium.createTime, '{y}/{m}/{d} {h}:{i}:{s}') }}
                <el-button type="text" size="mini" class="el-icon-delete" @click="handleDelete(medium.id)"></el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="文档" name="file">
        <el-row>
          <el-col :span="16" style="margin: 10px 0;">
            <span>文档素材（共{{total}}条）</span>
          </el-col>
          <el-col :span="6">
            <el-input placeholder="请输入文章标题进行搜索">
              <el-button slot="append" icon="el-icon-search"></el-button>
            </el-input>
          </el-col>
          <el-col :span="2" align="right">
            <el-upload
              class="avatar-uploader"
              :action="uploadFileUrl"
              :headers="headers"
              accept=".pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx"
              :multiple="true"
              :show-file-list="false"
              :file-list="fileList"
              :before-upload="handleFileSizeLimit"
              :on-error="handleUploadError"
              :on-exceed="handleExceed"
              :on-success="handleMultiplUploadSuccess">
              <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
            </el-upload>
          </el-col>
        </el-row>
        <el-row :gutter="5" class="el-row" type="flex"  style="overflow:auto">
          <el-col :span="4" v-for = "(medium,index) in mediumList" :key="medium.id" class="el-col">
            <el-card :body-style="{padding:'4px'}">
              <div style="padding: 0px;">
                <span class="card-title">{{ medium.content.title}}</span>
                <el-row :gutter="0">
                  <el-col :span="16">
                    <span class="desc">{{ medium.content.desc }}</span>
                  </el-col>
                  <el-col :span="8">
                    <el-image
                      style="width: 50px; height: 50px;float: right"
                      :src="medium.content.imgUrl"
                      fit="fill"></el-image>
                  </el-col>
                </el-row>
              </div>
              <div class="bottom clearfix">
                创建:{{parseTime(medium.createTime, '{y}/{m}/{d} {h}:{i}:{s}') }}
                <el-button type="text" size="mini" class="el-icon-edit" @click="handleUpdate(medium.id)"></el-button>
                <el-button type="text" size="mini" class="el-icon-delete" @click="handleDelete(medium.id)"></el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="音频" name="audio">音频</el-tab-pane>
      <el-tab-pane label="视频" name="video">视频</el-tab-pane>
      <el-tab-pane label="小程序" name="miniprogram">小程序</el-tab-pane>
    </el-tabs>
    <!--文章编辑窗口 -->
    <el-dialog :title="title" :visible.sync="openNewsDialog" width="768px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="12">
          <el-col :span="18">
            <el-row>
              <el-input v-model="form.title" placeholder="请输入文章标题" />
            </el-row>
            <el-row>
              <el-input v-model="form.desc" placeholder="请输入文章摘要" />
            </el-row>
          </el-col>
          <el-col :span="6">
            <el-upload
              class="avatar-uploader"
              :action="uploadFileUrl"
              :headers="headers"
              :multiple="false"
              :show-file-list="false"
              :file-list="fileList"
              :on-error="handleUploadError"
              :on-exceed="handleExceed"
              :on-success="handleUploadSuccess"
              :on-change="handleChange">
              <img v-if="imgUrl" :src="imgUrl" class="avatar">
              <div v-else>
                <i class="el-icon-plus avatar-uploader-icon" style="vertical-align: center"></i>
                <span>封面图片</span>
              </div>
            </el-upload>
          </el-col>
          <el-col :span="24">
            <editor v-model="form.content" :min-height="240"/>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--链接编辑窗口 -->
    <el-dialog :title="title" :visible.sync="openLinkDialog" width="768px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="链接地址" prop="link" :rules="[{type:'url',message: '链接地址必须以http或https开头'}]">
              <el-input v-model="form.link" v-model.number="form.link" placeholder="链接地址请以http或https开头" @change="requestTDK"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="链接标题" prop="noticeTitle">
              <el-input v-model="form.title" placeholder="请输入链接标题" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="链接描述" prop="noticeTitle">
              <el-input type="textarea" v-model="form.desc" placeholder="请输入链接描述" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="封面图" prop="noticeTitle">
              <el-upload
                class="avatar-uploader"
                :action="uploadFileUrl"
                :headers="headers"
                :multiple="false"
                :show-file-list="false"
                :file-list="fileList"
                :on-error="handleUploadError"
                :on-exceed="handleExceed"
                :on-success="handleUploadSuccess"
                :on-change="handleChange">
                <img v-if="imgUrl" :src="imgUrl" class="avatar">
                <div v-else>
                  <i class="el-icon-plus avatar-uploader-icon" style="vertical-align: center"></i>
                  <span>封面图片</span>
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { listMedium, getMedium, delMedium, addMedium, updateMedium, exportMedium } from "@/api/wework/medium";
import axios from 'axios'
import Editor from '@/components/Editor';
import {addNotice, updateNotice} from "@/api/system/notice";
import {getToken} from "@/utils/auth";
import {extractMeta} from "@/utils/requestTDK";
import {getRole} from "@/api/system/role";
export default {
  components: {Editor},
  data() {
    return {
      //按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 总条数
      total: 0,
      // 素材库 表格数据
      mediumList: [],
      link:undefined,
      // 非多个禁用
      multiple: true,
      type: 'news',
      tabLabel: '文章',
      currentDate: new Date(),
      url:'http://scrm-mochat.oss-cn-beijing.aliyuncs.com/contact/avatar/1/82533d91f106e55ddbca19bef959f741.png?Expires=1626836646&OSSAccessKeyId=LTAI5tL1jwaCjV6k3sjuAJBf&Signature=NutGxC5dNYHAO8shXY63HYgrltA%3D',
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      openNewsDialog: false,
      openLinkDialog: false,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      imgUrl:undefined,
      imgPath:undefined,
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      updateTitleFlagArray:[],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: undefined,
        content: undefined,
        tags: undefined,
      },
      // 表单参数
      form: {},
      fileList:[],
      // 表单校验
      rules: {
        title: [
          { required: true, message: "文章标题不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "文章不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询素材库 列表 */
    getList() {
      this.loading = true;
      this.queryParams.type = this.type;
      listMedium(this.queryParams).then(response => {
        this.mediumList = response.rows;
        //对content parse
        this.mediumList.forEach(m=>m.content=JSON.parse(m.content));
        this.updateTitleFlagArray = this.mediumList.map(m=>false);
        this.total = response.total;
        this.loading = false;
      });
    },
    handleTabClick(tab, event) {
      this.tabLabel = tab.label;
      this.getList();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        title: undefined,
        content: undefined,
      };
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd(){
      this.reset();
      this.openDialog('新增');
    },
    openDialog(operator){
      this.title = operator+this.tabLabel;
      if (this.type === 'news'){
        this.openNewsDialog = true;
      }else if (this.type === 'link'){
        this.openLinkDialog = true;
      }
    },
    handleUpdate(mediumId){
      getMedium(mediumId).then(response => {
        let medium = response.data;
        this.form = JSON.parse(medium.content);
        this.form.id = medium.id;
        this.imgUrl = this.form.imgUrl;
        this.openDialog('编辑');
      });
    },
    handleDelete(mediumId){
      this.$confirm('此操作将永久删除该素材, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delMedium(mediumId).then(response=>{
          this.msgSuccess("删除成功");
          this.getList();
        }).catch(() => {});
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 取消按钮
    cancel() {
      this.openNewsDialog = false;
      this.openLinkDialog = false;
      this.reset();
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          this.form.imgPath = this.imgPath;
          const content = this.form;
          const medium = {'id':this.form.id,'type':this.type,'content':JSON.stringify(content)};
          if (this.form.id != null) {
            updateMedium(medium).then(response => {
              this.buttonLoading = false;
              this.msgSuccess("修改成功");
              this.cancel();
              this.getList();
            });
          } else {
            addMedium(medium).then(response => {
              this.buttonLoading = false;
              this.msgSuccess("新增成功");
              this.cancel();
              this.getList();
            });
          }
        }
      });
    },
    // 文件个数超出
    handleExceed() {
      this.$message.error(`只允许上传单个文件`);
    },
    handleFileSizeLimit(file){
      //
      const isLimit20M = file.size / 1024 / 1024 < 20;
      if (!isLimit20M){
        this.$message.error('上传文件大小不能超过 20MB!');
      }
    },
    // 上传失败
    handleUploadError(err) {
      this.$message.error("上传失败, 请重试");
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw);
      if (res.code == '200'){
        this.$message.success("上传成功");
        this.imgUrl = res.data.url;
        this.imgPath = res.data.path;
      }else{
        this.$message.error(res.msg);
      }
    },
    // 上传成功回调
    handleMultiplUploadSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw);
      if (res.code == '200'){
        const content = {title:file.name,imgPath:res.data.path};
        const medium = {type:this.type,content:JSON.stringify(content)};
        addMedium(medium).then(response => {
          this.getList();
        });
      }else {
        this.$message.error(res.msg);
      }

    },
    handleUpdateTitle(index,mediumId){
      this.$set(this.updateTitleFlagArray, index, true);
      console.log(this.$refs)
      console.log(this.$refs['input' + index][0])
      this.$refs['input' + index][0].focus();
    },
    updateTitle(index,medium){
      let newMedium = Object.assign({}, medium);;
      newMedium.content = JSON.stringify(medium.content);
      console.log(newMedium)
      console.log(medium)
      updateMedium(newMedium).then(response => {
        this.$set(this.updateTitleFlagArray, index, false);
        this.msgSuccess("修改成功");
      });

    },
    //上传文件让第二次覆盖第一的文件
    handleChange(file,fileList){
      if (fileList.length>0) {
        this.fileList=[fileList[fileList.length-1]]
      }
    },
    requestTDK(url) {
      extractMeta(url, (err,res)=>{
        this.form.title = res.title;
        this.form.desc = res.description;
        //TODO 有些网站禁止跨域获取图片(例如公众号中文章)，可考虑服务端伪造referer和host来获取(浏览器中禁止)
        this.imgUrl = res.imgUrl;
      })
    }
  }
}
</script>
<style scoped="scoped" lang="scss">
.el-card{
  min-width: 100%;
  height: 100%;
  margin-right: 20px;
  font-size: 12px;

  .desc{
    overflow : hidden;
    text-overflow: ellipsis;
    display:-webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    color: #97a8be;
    font-size: 8px;
  }
  .cart-title{
    font-weight: bold;
  }

}
.bottom {
  color: #999;
  margin-top: 20px;
  line-height: 12px;
}


.el-row {
  margin-bottom: 3px;
  display: flex;
  flex-wrap: wrap
}
.el-col {
  border-radius: 4px;
  align-items: stretch;
  margin-bottom: 5px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 90px;
  height: 90px;
  line-height: 90px;
  text-align: center;
}
.avatar {
  width: 72px;
  height: 72px;
  display: block;
}
</style>
